package be.idamf.profiler
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	import flash.system.System;
	import flash.utils.Dictionary;
	import flash.utils.Timer;
	
	[Event(name="complete", type="flash.events.Event")]
	
	/**
	 * Profiler Utility that dispatches an Event.COMPLETE
	 * when the VM Garbage Collector has run (check is done every 2 seconds).
	 */
	public class GarbageCollector extends EventDispatcher
	{
		private static const SPRITE:Sprite = new Sprite();
		private static const INTERVAL:int = 2000;
		private static const CHECK:Dictionary = new Dictionary(true);
		
		protected var timer:Timer;
		
		/**
		 * @private
		 */
		public function GarbageCollector():void
		{
			timer = new Timer(INTERVAL);
			timer.start();
			timer.addEventListener(TimerEvent.TIMER, timerHandler);
			
			CHECK[SPRITE.addChild(new Sprite())] = true;
		}
		
		/**
		 * Runs the GC by executing System.gc() twice.
		 */
		public function run():void
		{
			System.gc();
			System.gc();
			
			timerHandler(null);
		}
		
		/**
		 * @private
		 */
		protected function timerHandler(event:Event):void
		{
			var isComplete:Boolean = true;
			
			for (var weak:Object in CHECK)
			{
				isComplete = false;
				break;
			}
			
			if (isComplete)
			{
				CHECK[SPRITE.addChild(new Sprite())] = true;
				dispatchEvent(new Event(Event.COMPLETE));
			}
			else
			{
				while (SPRITE.numChildren != 0)
					SPRITE.removeChildAt(0);
			}
		}
	}
}